package org.ansel.tools.eza;

import java.io.*;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;

//import org.apache.tools.zip.ZipFile;
import com.alibaba.fastjson2.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONObject;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;

public class GenerateRvtlist {
	/** 用于生成文件列表结果。*/
	private static Logger loggerRvt = null;
	/** 正常的日志文件。*/
	private static Logger logger = null;
	public GenerateRvtlist(){
		LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
		/*
		String logbackConfigPath = this.getClass().getResource("/eza/logback4Rvt.xml").toString();// 读取包内配置文件，一般静态
		//logbackConfigPath=System.getProperty("user.dir")+"/eza/logback4Rvt.xml";//读取jar包运行路径的参数文件，一般动态。
		logbackConfigPath=logbackConfigPath.replace("file:", "");
        if (logbackConfigPath != null) {}
		 */

		try {
			JoranConfigurator configurator = new JoranConfigurator();
			configurator.setContext(loggerContext);
			loggerContext.reset();
//			configurator.doConfigure(logbackConfigPath);
			InputStream is = this.getClass().getResourceAsStream("/eza/logback4Rvt.xml");
			configurator.doConfigure(is);
		} catch (Exception e) {
			e.printStackTrace();
		}

        loggerRvt=loggerContext.getLogger("rvtfile");
        logger=loggerContext.getLogger(this.getClass());
	}
	private static volatile GenerateRvtlist thisclass;
	public static GenerateRvtlist getInstance(){
		if(thisclass==null){
			synchronized (GenerateRvtlist.class) {
				if(thisclass==null){
					thisclass = new GenerateRvtlist();
				}
			}
		}
		return thisclass;
	}
	/** 压缩包路径前缀  */
	private static final String zippathprefix="D:/user/01382407/Downloadsv模型/";//TODO by zj dev
//	private static final String zippathprefix="/app/bdip/bdip-tomcat/webapps/static";//TODO by zj prd

	public void testLog(){
		logger.info("classpath="+this.getClass().getResource("/").toString());
	}
	/** 查询相对路径eza/zippathfile.txt内的zip路径文件，遍历所有zip文件，导出所有压缩包内的文件名，写入logs/revt.txt。
	 *
	 */
	public void scanZip() {
		logger.debug("classpath="+this.getClass().getResource("/").toString());
		String zippathfile = this.getClass().getResource("/config/zippathfile.txt").toString();//TODO by zj 读取包外配置文件

		zippathfile=System.getProperty("user.dir")+"/config/eza/zippathfile.txt";
		zippathfile=zippathfile.replace("file:","");
		logger.debug("zip文件列表"+zippathfile);
        try {
        	Scanner scanner = new Scanner(new File(zippathfile));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String zippath=zippathprefix+line;
                unzipByJdk(zippath);
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	logger.error(e.getMessage(), e);
        }
    }
	public void unzipByJdk(String zippath) {
		JSONObject jo=null;
		if(!zippath.endsWith(".zip")) {
			jo=new JSONObject();
			jo.put("zipPath", zippath);
			loggerRvt.info(jo.toString());
			return;
		}
		try {
            java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(zippath,java.nio.charset.Charset.forName("GBK"));
            Enumeration<?> entries = zipFile.entries();
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            while (entries.hasMoreElements()) {
            	java.util.zip.ZipEntry entry = (ZipEntry) entries.nextElement();
                jo=new JSONObject();
    			jo.put("zipPath", zippath);
    			jo.put("entryName", entry.getName());
    			jo.put("isDirectory", entry.isDirectory());
    			jo.put("size", entry.getSize());
    			jo.put("date", df.format(new java.util.Date(entry.getTime())));
    			loggerRvt.info(jo.toString());
                logger.debug( String.format("unzipByJdk():unzipping %s ,isDirectory:%s,size:%s,date:%s",new Object[] {entry.getName(),Boolean.valueOf(entry.isDirectory()),Long.valueOf(entry.getSize()),df.format(new java.util.Date(entry.getTime()))} ) );
            }
            zipFile.close();
        } catch (Exception e) {
            e.printStackTrace();
			logger.error("unzipByJdk_"+zippath,e);
        }
	}
	/** 用apache组件解压。文件被固定解压到logs/模型/ 路径下，平铺
	 * @param1 zipPath 压缩包文件的绝对地址
//	 * @param1 innerpath 压缩包内某个文件的路径，或者rvt文件名
	 */
	public void getFilefromZip(String zippath,String innerpath) {
		logger.debug(String.format("begin to download {zippath:%s,innerpath:%s} ",zippath,innerpath));
		String filename="";
		String[] tmp=innerpath.split("/");
		filename=tmp[tmp.length-1];
		// 文件被固定解压到logs/模型 路径下，平铺
		// 模型/EHE-CP-AS0103-E_动力站BA系统、电力监控系统模型_V3.0.rvt
		FileOutputStream fos =null;
		java.util.zip.ZipInputStream zipInputStream=null;
		try {
			 zipInputStream = new java.util.zip.ZipInputStream(new FileInputStream(zippath),Charset.forName("GBK"));
			java.util.zip.ZipEntry entry=null;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (!entry.isDirectory() && entry.getName().indexOf(filename)>-1) {//entry.getName().equals(innerpath)
					String outputfullpath=System.getProperty("user.dir").replace("file:","")+"/logs/"+filename;
					fos = new FileOutputStream(new File(outputfullpath));
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = zipInputStream.read(buffer)) > 0) {
                    	fos.write(buffer, 0, length);
                    }
					logger.info(String.format("{zippath:%s,innerpath:%s} downloaded.",zippath,innerpath));
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
			logger.error(String.format("ERROR_getFilefromZip_{zippath:%s,innerpath:%s} .",zippath,innerpath),e);
        } finally {
			try {
				if (zipInputStream != null) zipInputStream.close();
				if (fos != null) fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
	public void batchGetFilefromZip(String jsonPropFilePath) {
		File jsonPropFile = new File(jsonPropFilePath);
		Reader reader= null;
		try {
			reader = new InputStreamReader(new FileInputStream(jsonPropFile),"UTF-8");
			int ch=0;
			StringBuilder sb = new StringBuilder();
			while((ch=reader.read())!=-1){
				sb.append((char)ch);
			}
			JSONArray ja = JSONArray.parse(sb.toString());
			for(int i=0;i<ja.size();i++){
				JSONObject jsonObject = ja.getJSONObject(i);
				String zippath=jsonObject.getString("zippath");
				String innerpath=jsonObject.getString("innerpath");
				this.getFilefromZip(zippath,innerpath);
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		} catch (FileNotFoundException e) {
			logger.error("jsonPropFilePath"+jsonPropFilePath,e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			try {
				reader.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}

	}

	/** 用apache组件解压。
	 * @param1 zipPath 压缩包文件的绝对地址
	 * @param1 unzipPath 解压文件夹路径
	 
	public void unzipByApache(String zipPath) {
		JSONObject jo=null;
		if(!zipPath.endsWith(".zip")) {
			jo=new JSONObject();
			jo.put("zipPath", zipPath);
			loggerRvt.info(jo.toString());
			return;
		}
		org.apache.tools.zip.ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(zipPath, "GBK");
		} catch (IOException e) {
			e.printStackTrace();
		}
		Enumeration<?> entries = zipFile.getEntries();
		logger.debug("unzipByApache():"+"zipfile "+zipPath);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		while (entries.hasMoreElements()) {
			org.apache.tools.zip.ZipEntry entry = (org.apache.tools.zip.ZipEntry) entries.nextElement();
			jo=new JSONObject();
			jo.put("zipPath", zipPath);
			jo.put("entryName", entry.getName());
			jo.put("isDirectory", entry.isDirectory());
			jo.put("size", entry.getSize());
			jo.put("date", df.format(new java.util.Date(entry.getTime())));
			loggerRvt.info(jo.toString());
			logger.debug( String.format("unzipByApache():unzipping %s ,isDirectory:%s,size:%s,date:%s", entry.getName(), Boolean.toString(entry.isDirectory()), Long.toString(entry.getSize()), df.format(new java.util.Date(entry.getTime()))) );
		}
	}*/
	
	public static void main(String[] args) {

		System.out.println("user.dir="+System.getProperty("user.dir"));
		GenerateRvtlist service = GenerateRvtlist.getInstance();
		if(args.length==0) {
			service.testLog();
		}else if(args.length>0 && "getFilefromZip".equals(args[0])) {
			String jsonPropFilePath="/config/eza/getFilefromZipParams.json";
			try{
				jsonPropFilePath=args[1];
			} catch (Exception ex){

			}
			jsonPropFilePath=System.getProperty("user.dir").replace("file:","")+"/"+jsonPropFilePath;
			service.batchGetFilefromZip(jsonPropFilePath);
		} else if ("scanZip".equals(args[0])) {
			service.scanZip();
		}

	}
}
